package com.cloud.wms.ui.in.register;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.eventBus.EventBusUtil;
import com.cloud.core.utils.DateUtil;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.utils.TimeUtils;
import com.cloud.core.utils.ValidateUtils;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.CacheConfig;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.tools.DatePickerUtils;
import com.cloud.wms.ui.in.contract.InRegisterContract;
import com.cloud.wms.ui.in.entity.InOrderEntity;
import com.cloud.wms.ui.in.presnter.InRegisterPresenter;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.utils.CarKeyboardUtil;
import com.squareup.picasso.Picasso;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-21 15:36
 * @Description:
 */
public class InRegisterActivity extends BaseBarListActivity<String, InRegisterPresenter> implements InRegisterContract.View, View.OnTouchListener {
    private static final int REQUEST_CODE = 0x1001;
    @BindView(R.id.et_plate)
    EditText etPlate;
    @BindView(R.id.et_volume)
    EditText etVolume;
    @BindView(R.id.et_box_amount)
    EditText etBoxAmount;
    @BindView(R.id.et_date)
    TextView etDate;
    @BindView(R.id.btn_part)
    CheckedTextView btnPart;
    @BindView(R.id.btn_all)
    CheckedTextView btnAll;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private static final int MAX_IMG_COUNT = 4;
    private int mImageResize;
    private static final String ADD_TAG = "IMG";
    private InOrderEntity inOrder;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            verifyRequired();
        }
    };
    private DatePickerDialog mDateDialog;
    private TaskEntity taskEntity;
    private String beginTime;
    private CarKeyboardUtil carKeyboardUtil;

    @Override
    protected String barTitle() {
        return "到货登记";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_in_register;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_select_photo;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        super.initEvent();
        beginTime = TimeUtils.getCurrentDateAndTime();
        inOrder = getIntent().getParcelableExtra(IntentKey.OBJECT_KEY);
        taskEntity = getIntent().getParcelableExtra(IntentKey.TASK_KEY);
        btnSubmit.setEnabled(false);
        ArrayList<String> list = new ArrayList<>();
        list.add(ADD_TAG);
        mAdapter.setNewInstance(list);
        mAdapter.addChildClickViewIds(R.id.iv_delete);

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mAdapter.removeAt(position);
            if (!ADD_TAG.equals(mAdapter.getData().get(mAdapter.getData().size() - 1))) {
                mAdapter.addData(ADD_TAG);
            }
        });
        etVolume.addTextChangedListener(textWatcher);
        etBoxAmount.addTextChangedListener(textWatcher);
        etDate.setText(TimeUtils.getCurrentDate());
        carKeyboardUtil = new CarKeyboardUtil(InRegisterActivity.this, etPlate);
        etPlate.setOnTouchListener(this);
        etVolume.setOnTouchListener(this);
        etBoxAmount.setOnTouchListener(this);
        etDate.setOnTouchListener(this);
        etRemark.setOnTouchListener(this);
        etPlate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = s.toString();
                if (text.contains("港") || text.contains("澳") || text.contains("学")) {
                    etPlate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)});
                } else {
                    etPlate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
                }
                //没有输入内容时软键盘重置为省份简称软键盘
                if (text.length() == 0) {
                    carKeyboardUtil.changeKeyboard(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, String item) {
        helper.setGone(R.id.iv_delete, item.equals(ADD_TAG));
        ImageView imageView = (ImageView) helper.getView(R.id.iv_select_photo);
        int resize = getItemResize();
        if (!item.equals(ADD_TAG))
            Picasso.with(this).load("file://" + item)
                    .placeholder(R.mipmap.icon_image_holder)
                    .resize(resize, resize)
                    .centerCrop()
                    .into(imageView);
        else
            Picasso.with(this).load("file://" + item)
                    .placeholder(R.mipmap.icon_picture_add)
                    .into(imageView);
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(this, 2);
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(2)
                .verticalDivider(ContextCompat.getDrawable(this, R.color.white), DensityUtils.Dp2Px(this, 6), false)
                .horizontalDivider(ContextCompat.getDrawable(this, R.color.white), DensityUtils.Dp2Px(this, 6), false)
                .build();
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<String, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
        if (ADD_TAG.equals(mAdapter.getData().get(position)) && MAX_IMG_COUNT > mAdapter.getData().size() - 1) {
            selectPhoto(mAdapter.getData().size() - 1);
        }
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
        switch (message.what) {
            case InRegisterPresenter.IN_REGISTER_SUBMIT:
                success("到货登记成功！");
                EventBusUtil.sendEvent(new Event<>(EventConfig.TASK_REFRESH));
                this.finish();
                break;
        }
    }

    @OnClick({R.id.et_date, R.id.btn_part, R.id.btn_all, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_date:
                dateSelector();
                break;
            case R.id.btn_part:
                btnPart.setChecked(true);
                btnAll.setChecked(false);
                break;
            case R.id.btn_all:
                btnPart.setChecked(false);
                btnAll.setChecked(true);
                break;
            case R.id.btn_submit:
                verifySubmit();
                break;
        }
    }

    private void verifyRequired() {
        String plate = etPlate.getText().toString().trim();
        if (TextUtils.isEmpty(plate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String volume = etVolume.getText().toString().trim();
        if (TextUtils.isEmpty(volume)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String boxAmount = etBoxAmount.getText().toString().trim();
        if (TextUtils.isEmpty(boxAmount)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String date = etDate.getText().toString().trim();
        if (TextUtils.isEmpty(date)) {
            btnSubmit.setEnabled(false);
            return;
        }
        btnSubmit.setEnabled(true);
    }

    private void verifySubmit() {
        String plate = etPlate.getText().toString().trim();
        if (TextUtils.isEmpty(plate)) {
            info("车牌号为必填项");
            return;
        }
//        if (!ValidateUtils.checkVehicleNo(plate)) {
//            info("车牌号格式错误");
//            return;
//        }
        String volume = etVolume.getText().toString().trim();
        if (TextUtils.isEmpty(volume)) {
            info("到货体积为必填项");
            return;
        }
        if (!NumberUtils.isNumber(volume)) {
            info("到货体积为有效数字");
            return;
        }
        String boxAmount = etBoxAmount.getText().toString().trim();
        if (TextUtils.isEmpty(boxAmount)) {
            info("到货箱数为必填项");
            return;
        }
        if (!NumberUtils.isInt(boxAmount) || NumberUtils.getIntegerValue(boxAmount) <= 0) {
            info("到货箱数必须为整数且必须大于0");
            return;
        }
        String date = etDate.getText().toString().trim();
        if (TextUtils.isEmpty(date)) {
            info("到货时间为必填项");
            return;
        }
        boolean isAll = btnAll.isChecked();
        String remark = etRemark.getText().toString().trim();

        ArrayList<String> list = new ArrayList<>(mAdapter.getData());
        if (mAdapter.getData().size() < MAX_IMG_COUNT)
            list.remove(list.size() - 1);

        mPresenter.submitRegisterTask(
                taskEntity,
                inOrder,
                plate,
                volume,
                boxAmount,
                date,
                isAll,
                remark,
                list, beginTime);
    }

    private int getItemResize() {
        if (mImageResize == 0) {
            RecyclerView.LayoutManager lm = rvList.getLayoutManager();
            int spanCount = ((GridLayoutManager) lm).getSpanCount();
            int screenWidth = this.getResources().getDisplayMetrics().widthPixels;
            int availableWidth = screenWidth - 6 * (spanCount - 1);
            mImageResize = availableWidth / spanCount;
        }
        return mImageResize;
    }

    private void selectPhoto(int size) {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, CacheConfig.AUTHORITY))
                .maxSelectable(MAX_IMG_COUNT - size)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new PicassoEngine())
                .showSingleMediaType(true)
                .originalEnable(true)
                .maxOriginalSize(10)
                .autoHideToolbarOnSingleTap(true)
                .theme(R.style.Matisse_Dracula)
                .forResult(REQUEST_CODE);
    }

    private void dateSelector() {
        mDateDialog = DatePickerUtils.datePicker(this,
                false,
                (view, year, month, dayOfMonth) -> {
                    String date = DateUtil.formatYMD(year, month + 1, dayOfMonth);
                    etDate.setText(date);
                    verifyRequired();
                });
        mDateDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            List<String> imagePaths = Matisse.obtainPathResult(data);
            List<String> adapterData = mAdapter.getData();
            adapterData.remove(adapterData.size() - 1);
            adapterData.addAll(imagePaths);
            if (adapterData.size() < MAX_IMG_COUNT) {
                adapterData.add(ADD_TAG);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    public static void start(Context context, InOrderEntity inOrderEntity) {
        Intent intent = new Intent(context, InRegisterActivity.class);
        intent.putExtra(IntentKey.OBJECT_KEY, inOrderEntity);
        context.startActivity(intent);
    }

    public static void start(Context context, TaskEntity taskEntity, InOrderEntity inOrderEntity) {
        Intent intent = new Intent(context, InRegisterActivity.class);
        intent.putExtra(IntentKey.OBJECT_KEY, inOrderEntity);
        intent.putExtra(IntentKey.TASK_KEY, taskEntity);
        context.startActivity(intent);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (view.getId() == R.id.et_plate) {
            carKeyboardUtil.hideSystemKeyBroad();
            carKeyboardUtil.hideSoftInputMethod();
            if (!carKeyboardUtil.isShow())
                carKeyboardUtil.showKeyboard();
        } else {
            if (carKeyboardUtil.isShow())
                carKeyboardUtil.hideKeyboard();
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (carKeyboardUtil.isShow()) {
                carKeyboardUtil.hideKeyboard();
            } else
                finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
